package me.macd.mindoc.dao.impl;

import me.macd.mindoc.dao.MemberDao;
import me.macd.mindoc.model.MemberRelationshipResult;
import me.macd.mindoc.model.Members;
import me.macd.mindoc.util.DefaultNameHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-10-10
 * @create: 2018-10-10 20:43
 */
@Repository
public class MemberDaoJDBCTemplateImpl implements MemberDao {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public MemberDaoJDBCTemplateImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int countForUsersByBookId(int bookId) {
        String sql = "SELECT count(*) AS total_count FROM md_relationship AS rel" +
                " LEFT JOIN md_members as member ON rel.member_id = member.member_id" +
                " WHERE rel.book_id = ?";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, bookId);
        return count == null ? 0 : count;
    }

    @Override
    public List<MemberRelationshipResult> findForUsersByBookId(int bookId, int start, int pageSize) {
        String sql = "SELECT * FROM md_relationship AS rel" +
                " LEFT JOIN md_members as member ON rel.member_id = member.member_id" +
                " WHERE rel.book_id = ?" +
                " ORDER BY rel.relationship_id DESC LIMIT ?,?";
        return jdbcTemplate.query(sql, new Object[]{bookId, start, pageSize},
                new CommonRowMapper<>(MemberRelationshipResult.class, new DefaultNameHandler()));
    }

    @Override
    public Members findByAccount(String account) {
        String sql = "SELECT * FROM md_members WHERE account=?";
        return jdbcTemplate.queryForObject(sql, new CommonRowMapper<>(Members.class, new DefaultNameHandler()), account);
    }

    @Override
    public Members findByPrimaryKey(int key) {
        String sql = "SELECT * FROM md_members WHERE member_id=?";
        return jdbcTemplate.queryForObject(sql, new CommonRowMapper<>(Members.class, new DefaultNameHandler()), key);
    }

    @Override
    public int update(Members member) {
        return new CommonDao(jdbcTemplate).update(member);
    }
}
